{% extends "base.html" %}

{% block title %}取消预约 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}取消预约{% endblock %}

{% block extra_css %}
<style>
    .cancel-container {
        max-width: 600px;
        margin: 0 auto;
    }

    .reservation-summary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        padding: 25px;
        margin-bottom: 30px;
        position: relative;
    }

    .reservation-summary::before {
        content: '';
        position: absolute;
        top: -2px;
        left: -2px;
        right: -2px;
        bottom: -2px;
        background: linear-gradient(45deg, #ff6b6b, #ee5a52, #ff6b6b);
        border-radius: 12px;
        z-index: -1;
        animation: borderAnimation 3s ease-in-out infinite;
    }

    @keyframes borderAnimation {
        0%, 100% { transform: rotate(0deg); }
        50% { transform: rotate(180deg); }
    }

    .warning-card {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .warning-title {
        color: #856404;
        font-weight: 600;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
    }

    .warning-title i {
        margin-right: 10px;
        font-size: 1.2rem;
    }

    .warning-content {
        color: #856404;
        line-height: 1.6;
    }

    .cancel-form {
        background: white;
        border-radius: 12px;
        padding: 30px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .form-section {
        margin-bottom: 25px;
    }

    .form-section:last-child {
        margin-bottom: 0;
    }

    .section-title {
        font-weight: 600;
        color: #495057;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
    }

    .section-title i {
        margin-right: 10px;
        color: #007bff;
    }

    .reason-option {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
    }

    .reason-option:hover {
        border-color: #007bff;
        background: #f8f9ff;
    }

    .reason-option.selected {
        border-color: #007bff;
        background: #e3f2fd;
    }

    .reason-option input[type="radio"] {
        margin-right: 12px;
    }

    .reason-text {
        flex: 1;
    }

    .reason-description {
        font-size: 0.85rem;
        color: #6c757d;
        margin-top: 5px;
    }

    .policy-info {
        background: #e3f2fd;
        border: 1px solid #bbdefb;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
    }

    .policy-title {
        color: #1976d2;
        font-weight: 600;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
    }

    .policy-title i {
        margin-right: 10px;
    }

    .policy-content {
        color: #1976d2;
        line-height: 1.6;
    }

    .policy-list {
        margin: 10px 0;
        padding-left: 20px;
    }

    .policy-list li {
        margin-bottom: 8px;
    }

    .action-buttons {
        background: white;
        border-radius: 12px;
        padding: 25px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        text-align: center;
    }

    .btn-cancel-confirm {
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
        border: none;
        color: white;
        padding: 12px 30px;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.2s ease;
    }

    .btn-cancel-confirm:hover {
        background: linear-gradient(135deg, #ee5a52 0%, #ff6b6b 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(238, 90, 82, 0.3);
        color: white;
    }

    .countdown-timer {
        background: #f8d7da;
        border: 1px solid #f5c6cb;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        text-align: center;
    }

    .countdown-timer .timer-title {
        color: #721c24;
        font-weight: 600;
        margin-bottom: 10px;
    }

    .countdown-timer .timer-value {
        font-size: 1.5rem;
        font-weight: bold;
        color: #721c24;
    }

    .notes-helper {
        font-size: 0.85rem;
        color: #6c757d;
        margin-top: 5px;
        line-height: 1.4;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="cancel-container">
        <!-- 返回按钮 -->
        <div class="mb-3">
            <a href="{{ url_for('student_reservations.detail', reservation_id=reservation.id) }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> 返回预约详情
            </a>
        </div>

        <!-- 预约摘要 -->
        <div class="reservation-summary">
            <h5 class="mb-3">
                <i class="bi bi-calendar-x"></i>
                取消预约确认
            </h5>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-2">
                        <strong>预约日期：</strong>
                        {{ reservation.reservation_date.strftime('%Y年%m月%d日') }}
                    </div>
                    <div class="mb-2">
                        <strong>上课时间：</strong>
                        {{ reservation.start_time.strftime('%H:%M') }} - {{ reservation.end_time.strftime('%H:%M') }}
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-2">
                        <strong>教练：</strong>
                        {{ reservation.coach.real_name }}
                    </div>
                    <div class="mb-2">
                        <strong>球台：</strong>
                        {{ reservation.table.name }}
                    </div>
                </div>
            </div>
            <div class="mt-3 pt-3 border-top border-light border-opacity-25">
                <div class="row">
                    <div class="col-md-6">
                        <strong>课程费用：</strong>
                        ¥{{ "%.2f"|format(reservation.get_price_yuan()) }}
                    </div>
                    <div class="col-md-6">
                        <strong>预约状态：</strong>
                        {{ reservation.get_status_display() }}
                    </div>
                </div>
            </div>
        </div>

        <!-- 倒计时提醒（如果接近截止时间） -->
        {% if reservation.can_be_cancelled() %}
            {% set hours_until_start = ((reservation.get_datetime_start() - moment.utcnow()).total_seconds() / 3600) | int %}
            {% if hours_until_start <= 48 %}
            <div class="countdown-timer">
                <div class="timer-title">
                    <i class="bi bi-clock-history"></i>
                    取消截止时间倒计时
                </div>
                <div class="timer-value" id="countdownTimer">
                    计算中...
                </div>
                <small>距离预约开始前24小时的剩余时间</small>
            </div>
            {% endif %}
        {% endif %}

        <!-- 警告信息 -->
        <div class="warning-card">
            <div class="warning-title">
                <i class="bi bi-exclamation-triangle"></i>
                重要提醒
            </div>
            <div class="warning-content">
                <p><strong>请仔细阅读以下取消政策：</strong></p>
                <ul class="mb-0">
                    <li>取消预约必须在课程开始前24小时进行</li>
                    <li>频繁取消可能会影响您的预约信用记录</li>
                    <li>取消后的课程费用将根据取消政策进行处理</li>
                    <li>建议与教练沟通协商，寻找合适的解决方案</li>
                </ul>
            </div>
        </div>

        <!-- 取消表单 -->
        <div class="cancel-form">
            <form method="POST" id="cancelForm">
                {{ form.hidden_tag() }}

                <!-- 取消原因选择 -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="bi bi-chat-square-text"></i>
                        请选择取消原因
                    </div>

                    <div class="reason-options">
                        {% for value, label in form.cancel_reason.choices %}
                            {% if value %}
                            <div class="reason-option" onclick="selectReason('{{ value }}')">
                                <input type="radio" name="cancel_reason" value="{{ value }}" id="reason_{{ value }}">
                                <div class="reason-text">
                                    <div>{{ label }}</div>
                                    <div class="reason-description">
                                        {% if value == 'schedule_conflict' %}
                                            与其他安排产生冲突，无法按时参加
                                        {% elif value == 'personal_reason' %}
                                            个人或家庭原因，需要取消预约
                                        {% elif value == 'weather' %}
                                            天气原因影响出行或训练
                                        {% elif value == 'health' %}
                                            身体不适，不适合进行训练
                                        {% elif value == 'emergency' %}
                                            突发紧急情况，无法参加
                                        {% elif value == 'other' %}
                                            其他原因，请在下方详细说明
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                            {% endif %}
                        {% endfor %}
                    </div>

                    {% if form.cancel_reason.errors %}
                        <div class="text-danger small mt-2">
                            {% for error in form.cancel_reason.errors %}
                                <i class="bi bi-exclamation-circle"></i> {{ error }}
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>

                <!-- 补充说明 -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="bi bi-pencil-square"></i>
                        补充说明（可选）
                    </div>
                    {{ form.additional_notes(class="form-control", rows="4") }}
                    <div class="notes-helper">
                        请详细说明取消原因，这将有助于我们改进服务。如果是因为教练或课程安排问题，
                        我们会及时处理并为您提供更好的解决方案。
                    </div>
                    {% if form.additional_notes.errors %}
                        <div class="text-danger small mt-2">
                            {% for error in form.additional_notes.errors %}
                                <i class="bi bi-exclamation-circle"></i> {{ error }}
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
            </form>
        </div>

        <!-- 取消政策信息 -->
        <div class="policy-info">
            <div class="policy-title">
                <i class="bi bi-info-circle"></i>
                取消政策说明
            </div>
            <div class="policy-content">
                <p><strong>退费政策：</strong></p>
                <ul class="policy-list">
                    <li>提前24小时以上取消：全额退款</li>
                    <li>提前12-24小时取消：退款80%</li>
                    <li>提前12小时内取消：不予退款</li>
                    <li>因不可抗力因素（如极端天气）取消：全额退款</li>
                </ul>
                <p><strong>信用记录：</strong></p>
                <ul class="policy-list">
                    <li>每月允许取消3次预约，超出部分将记录不良信用</li>
                    <li>连续3次无故取消将暂停预约权限7天</li>
                    <li>建议优先与教练协商调整时间，而非直接取消</li>
                </ul>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <div class="mb-3">
                <h6>确认要取消这个预约吗？</h6>
                <small class="text-muted">此操作无法撤销，请谨慎决定</small>
            </div>

            <div class="d-flex justify-content-center gap-3">
                <a href="{{ url_for('student_reservations.detail', reservation_id=reservation.id) }}"
                   class="btn btn-outline-secondary btn-lg">
                    <i class="bi bi-arrow-left"></i> 不取消，返回
                </a>

                <button type="button" class="btn btn-cancel-confirm btn-lg" onclick="confirmCancel()" disabled id="confirmBtn">
                    <i class="bi bi-x-circle"></i> 确认取消预约
                </button>
            </div>

            <div class="mt-3">
                <small class="text-muted">
                    <i class="bi bi-telephone"></i>
                    如有疑问，请联系客服：400-123-4567
                </small>
            </div>
        </div>
    </div>
</div>

<!-- 确认取消模态框 -->
<div class="modal fade" id="confirmCancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">最后确认</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="bi bi-exclamation-triangle"></i>
                    您确定要取消这个预约吗？
                </div>
                <div class="text-center mb-3">
                    <strong>{{ reservation.reservation_date.strftime('%Y年%m月%d日') }}
                    {{ reservation.start_time.strftime('%H:%M') }}</strong>
                    <br>
                    与 <strong>{{ reservation.coach.real_name }}</strong> 的课程
                </div>
                <div class="mb-3">
                    <strong>取消原因：</strong>
                    <span id="confirmReason">未选择</span>
                </div>
                <div class="text-muted small">
                    取消后将按照取消政策处理退款，并记录在您的预约历史中。
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    再想想
                </button>
                <button type="button" class="btn btn-danger" onclick="submitCancel()">
                    确认取消
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let selectedReason = null;

// 选择取消原因
function selectReason(reason) {
    // 清除之前的选择
    document.querySelectorAll('.reason-option').forEach(option => {
        option.classList.remove('selected');
    });

    // 选择当前原因
    const selectedOption = document.querySelector(`input[value="${reason}"]`).closest('.reason-option');
    selectedOption.classList.add('selected');

    // 设置radio状态
    document.querySelector(`input[value="${reason}"]`).checked = true;
    selectedReason = reason;

    // 启用确认按钮
    document.getElementById('confirmBtn').disabled = false;

    // 更新确认模态框中的原因显示
    const reasonMap = {
        'schedule_conflict': '时间冲突',
        'personal_reason': '个人原因',
        'weather': '天气原因',
        'health': '身体不适',
        'emergency': '紧急情况',
        'other': '其他原因'
    };
    document.getElementById('confirmReason').textContent = reasonMap[reason] || reason;
}

// 确认取消（显示最终确认模态框）
function confirmCancel() {
    if (!selectedReason) {
        alert('请先选择取消原因');
        return;
    }

    const modal = new bootstrap.Modal(document.getElementById('confirmCancelModal'));
    modal.show();
}

// 提交取消请求
function submitCancel() {
    const form = document.getElementById('cancelForm');
    form.submit();
}

// 倒计时功能
{% if reservation.can_be_cancelled() %}
function updateCountdown() {
    const startTime = new Date('{{ reservation.get_datetime_start().isoformat() }}');
    const cancelDeadline = new Date(startTime.getTime() - 24 * 60 * 60 * 1000); // 24小时前
    const now = new Date();
    const diff = cancelDeadline - now;

    const timerElement = document.getElementById('countdownTimer');
    if (!timerElement) return;

    if (diff <= 0) {
        timerElement.innerHTML = '<span class="text-danger">已过取消截止时间</span>';
        // 禁用所有取消相关的控件
        document.getElementById('confirmBtn').disabled = true;
        document.querySelectorAll('.reason-option').forEach(option => {
            option.style.opacity = '0.5';
            option.style.pointerEvents = 'none';
        });
        return;
    }

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    let timeStr = '';
    if (days > 0) {
        timeStr = `${days}天 ${hours}小时 ${minutes}分钟`;
    } else if (hours > 0) {
        timeStr = `${hours}小时 ${minutes}分钟 ${seconds}秒`;
    } else {
        timeStr = `${minutes}分钟 ${seconds}秒`;
    }

    timerElement.textContent = timeStr;
}

// 每秒更新倒计时
setInterval(updateCountdown, 1000);
updateCountdown();
{% endif %}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 为所有取消原因选项添加点击事件
    document.querySelectorAll('.reason-option').forEach(option => {
        option.addEventListener('click', function() {
            const radio = this.querySelector('input[type="radio"]');
            if (radio) {
                selectReason(radio.value);
            }
        });
    });

    // 阻止点击radio时的事件冒泡
    document.querySelectorAll('.reason-option input[type="radio"]').forEach(radio => {
        radio.addEventListener('click', function(e) {
            e.stopPropagation();
            selectReason(this.value);
        });
    });

    // 如果有预设的原因，自动选择
    const preselectedReason = document.querySelector('input[name="cancel_reason"]:checked');
    if (preselectedReason) {
        selectReason(preselectedReason.value);
    }
});

// 防止意外离开页面
window.addEventListener('beforeunload', function(e) {
    if (selectedReason) {
        e.preventDefault();
        e.returnValue = '您正在取消预约，确定要离开页面吗？';
    }
});

// 表单提交时移除beforeunload监听
document.getElementById('cancelForm').addEventListener('submit', function() {
    window.removeEventListener('beforeunload', arguments.callee);
});
</script>
{% endblock %}